package dtd.PHS.VND_ExchangeRate.widget;

import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import dtd.PHS.VND_ExchangeRate.R;
import dtd.PHS.VND_ExchangeRate.data.DataProvider;
import dtd.PHS.VND_ExchangeRate.data.RateItem;
import dtd.PHS.VND_ExchangeRate.data.SJCItem;
import dtd.PHS.VND_ExchangeRate.data.VNExDatabase;
import dtd.PHS.VND_ExchangeRate.utils.Logger;

public class RatesUpdateReceiver extends BroadcastReceiver {

	private Context context;

	@Override
	public void onReceive(Context context, Intent intent) {
		this.context = context;
		Logger.logInfo("Received: " + context.getString(R.string.UPDATE_RATE_BROADCAST_INTENT));
		updateCurrencyRateWidgets();
	}

	private void updateCurrencyRateWidgets() {
		ArrayList<WidgetItem> allWidgetInfo = VNExDatabase.getAllWidgetInfo();
		for(WidgetItem v : allWidgetInfo) {
			if ( isRateInfo(v) ) {
				updateRate( v );
			}
		}
	}

	private void updateRate(WidgetItem v) {
		int id = v.getId();
		RateItem rate = DataProvider.getInstance().getRate(v.getCurrency());
		UpdateWidgetService.updateCurrencyWidget(context, id, rate);
	}

	private boolean isRateInfo(WidgetItem v) {
		if ( v.getCurrency().equals(SJCItem.SJC) ) return false;
		return true;
	}
}